# Setup MicroPython IntelliSense
# This script helps configure VS Code for MicroPython development

Write-Host "==================================" -ForegroundColor Cyan
Write-Host "MicroPython IntelliSense Setup" -ForegroundColor Cyan
Write-Host "==================================" -ForegroundColor Cyan
Write-Host ""

# Step 1: Detect Python
Write-Host "[1/5] Detecting Python..." -ForegroundColor Yellow
try {
    $pythonVersion = python --version 2>&1
    Write-Host "✓ Found: $pythonVersion" -ForegroundColor Green
} catch {
    Write-Host "✗ Python not found. Please install Python first." -ForegroundColor Red
    exit 1
}

# Step 2: Select platform
Write-Host ""
Write-Host "[2/5] Select your MicroPython platform:" -ForegroundColor Yellow
Write-Host "  1) ESP32"
Write-Host "  2) ESP8266"
Write-Host "  3) Raspberry Pi Pico (RP2)"
Write-Host "  4) STM32"
$platform = Read-Host "Enter choice (1-4)"

$stubPackage = switch ($platform) {
    "1" { "micropython-esp32-stubs" }
    "2" { "micropython-esp8266-stubs" }
    "3" { "micropython-rp2-stubs" }
    "4" { "micropython-stm32-stubs" }
    default {
        Write-Host "Invalid choice. Defaulting to ESP32." -ForegroundColor Yellow
        "micropython-esp32-stubs"
    }
}

# Step 3: Check if stubs are installed
Write-Host ""
Write-Host "[3/5] Checking for existing stubs..." -ForegroundColor Yellow
$stubInstalled = $false
try {
    $checkStubs = python -c "import $($stubPackage.Replace('-', '_')); print($($stubPackage.Replace('-', '_')).__path__[0])" 2>&1
    if ($LASTEXITCODE -eq 0) {
        $stubsPath = $checkStubs.Trim()
        Write-Host "✓ Stubs already installed at: $stubsPath" -ForegroundColor Green
        $stubInstalled = $true
    }
} catch {
    Write-Host "✗ Stubs not found." -ForegroundColor Yellow
}

# Step 4: Install stubs if needed
if (-not $stubInstalled) {
    Write-Host ""
    Write-Host "[4/5] Installing $stubPackage..." -ForegroundColor Yellow
    Write-Host "Running: pip install $stubPackage" -ForegroundColor Gray

    pip install $stubPackage

    if ($LASTEXITCODE -eq 0) {
        Write-Host "✓ Stubs installed successfully" -ForegroundColor Green

        # Get the installed path
        $stubsPath = python -c "import $($stubPackage.Replace('-', '_')); print($($stubPackage.Replace('-', '_')).__path__[0])" 2>&1
        $stubsPath = $stubsPath.Trim()
    } else {
        Write-Host "✗ Failed to install stubs" -ForegroundColor Red
        exit 1
    }
} else {
    Write-Host "[4/5] Skipping installation (already installed)" -ForegroundColor Green
}

# Step 5: Configure VS Code
Write-Host ""
Write-Host "[5/5] Configuring VS Code..." -ForegroundColor Yellow

# Create .vscode directory if it doesn't exist
$vscodeDir = ".vscode"
if (-not (Test-Path $vscodeDir)) {
    New-Item -ItemType Directory -Path $vscodeDir | Out-Null
    Write-Host "✓ Created .vscode directory" -ForegroundColor Green
}

# Read existing settings or create new
$settingsFile = Join-Path $vscodeDir "settings.json"
$settings = @{}

if (Test-Path $settingsFile) {
    Write-Host "  Found existing settings.json" -ForegroundColor Gray
    try {
        $settingsContent = Get-Content $settingsFile -Raw | ConvertFrom-Json
        $settings = @{}
        $settingsContent.PSObject.Properties | ForEach-Object {
            $settings[$_.Name] = $_.Value
        }
    } catch {
        Write-Host "  Warning: Could not parse existing settings.json" -ForegroundColor Yellow
    }
}

# Update Python analysis settings
if (-not $settings.ContainsKey("python.analysis.extraPaths")) {
    $settings["python.analysis.extraPaths"] = @()
}

$extraPaths = $settings["python.analysis.extraPaths"]
if ($extraPaths -is [string]) {
    $extraPaths = @($extraPaths)
}

# Add stubs path if not already present
if ($extraPaths -notcontains $stubsPath) {
    $extraPaths += $stubsPath
    $settings["python.analysis.extraPaths"] = $extraPaths
    Write-Host "✓ Added stubs to python.analysis.extraPaths" -ForegroundColor Green
} else {
    Write-Host "  Stubs path already in extraPaths" -ForegroundColor Gray
}

# Update autoComplete paths
if (-not $settings.ContainsKey("python.autoComplete.extraPaths")) {
    $settings["python.autoComplete.extraPaths"] = @()
}

$autoCompletePaths = $settings["python.autoComplete.extraPaths"]
if ($autoCompletePaths -is [string]) {
    $autoCompletePaths = @($autoCompletePaths)
}

if ($autoCompletePaths -notcontains $stubsPath) {
    $autoCompletePaths += $stubsPath
    $settings["python.autoComplete.extraPaths"] = $autoCompletePaths
    Write-Host "✓ Added stubs to python.autoComplete.extraPaths" -ForegroundColor Green
}

# Set other recommended settings
$settings["python.languageServer"] = "Pylance"
$settings["python.analysis.typeCheckingMode"] = "basic"

if (-not $settings.ContainsKey("python.analysis.diagnosticSeverityOverrides")) {
    $settings["python.analysis.diagnosticSeverityOverrides"] = @{}
}

$diagnostics = $settings["python.analysis.diagnosticSeverityOverrides"]
$diagnostics["reportMissingModuleSource"] = "none"
$diagnostics["reportMissingImports"] = "none"
$settings["python.analysis.diagnosticSeverityOverrides"] = $diagnostics

# Add MicroPython configuration
$settings["micropython.libraryPath"] = $stubsPath

# Save settings
$settingsJson = $settings | ConvertTo-Json -Depth 10
$settingsJson | Set-Content $settingsFile -Encoding UTF8
Write-Host "✓ Saved VS Code settings" -ForegroundColor Green

# Create test file
Write-Host ""
Write-Host "Creating test file..." -ForegroundColor Yellow
$testFile = "test_intellisense.py"
$testContent = @"
# MicroPython IntelliSense Test
# This file tests if IntelliSense is working correctly

from machine import Pin, ADC, PWM
from time import sleep
import network

# Test 1: Type hints and autocomplete
# Place cursor after the dot and press Ctrl+Space
led = Pin(2, Pin.OUT)
led.  # Should show: value, on, off, etc.

# Test 2: Hover for documentation
# Hover mouse over 'Pin' to see documentation
adc = ADC(0)

# Test 3: Parameter hints
# Place cursor inside parentheses to see parameter hints
pwm = PWM(Pin(5), freq=1000, duty=512)

# Test 4: Go to definition
# Ctrl+Click on 'Pin' to jump to definition
pin = Pin

# Test 5: Network API
wlan = network.WLAN(network.STA_IF)
wlan.  # Should show: active, connect, disconnect, etc.

# Test 6: Auto-import
# Try typing 'Timer' and see if it suggests importing from machine

print("IntelliSense test file created!")
"@

$testContent | Set-Content $testFile -Encoding UTF8
Write-Host "✓ Created $testFile" -ForegroundColor Green

# Summary
Write-Host ""
Write-Host "==================================" -ForegroundColor Cyan
Write-Host "Setup Complete!" -ForegroundColor Green
Write-Host "==================================" -ForegroundColor Cyan
Write-Host ""
Write-Host "Configuration:" -ForegroundColor Yellow
Write-Host "  Platform: $stubPackage" -ForegroundColor White
Write-Host "  Stubs path: $stubsPath" -ForegroundColor White
Write-Host "  Settings: $settingsFile" -ForegroundColor White
Write-Host ""
Write-Host "Next steps:" -ForegroundColor Yellow
Write-Host "  1. Reload VS Code window (Ctrl+Shift+P -> 'Reload Window')" -ForegroundColor White
Write-Host "  2. Open $testFile" -ForegroundColor White
Write-Host "  3. Test IntelliSense by typing 'led.' after line 10" -ForegroundColor White
Write-Host "  4. Try Ctrl+Click on 'Pin' to jump to definition" -ForegroundColor White
Write-Host ""
Write-Host "If IntelliSense doesn't work:" -ForegroundColor Yellow
Write-Host "  - Make sure Pylance extension is installed" -ForegroundColor White
Write-Host "  - Check Python interpreter is selected (bottom-right corner)" -ForegroundColor White
Write-Host "  - See SETUP_INTELLISENSE.md for more details" -ForegroundColor White
Write-Host ""
